package me.huha.service.api.impl;

import java.util.HashMap;
import java.util.Map;

import me.huha.entity.IpMessageEntity;
import me.huha.service.api.IpCityApiService;
import me.huha.util.HttpClientUtils;
import me.huha.util.IpUtils;
import me.huha.util.JsonUtils;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

/**
 * 根据IP地址获取详细的地域信息
 * 
 * @project:personGocheck
 * @class:AddressUtils.java
 * @author:heguanhua E-mail:37809893@qq.com
 * @date：Nov 14, 2012 6:38:25 PM
 */
public class TaoIpCityImpl implements IpCityApiService {
    
	private static Logger logger = Logger.getLogger(IpCityApiService.class);
	/**
	 * 淘宝接口URL
	 */
	private final static String TAOBAO_URL = "http://ip.taobao.com/service/getIpInfo.php";

	/**
	 * 根据IP和类型查找地区信息
	 * 
	 * @param ip
	 * @param apiType
	 * @return
	 */
	public IpMessageEntity getAddresses(String ip) {
		IpMessageEntity ipMessage = new IpMessageEntity();
		Map<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("ip", ip);
		String retstring = HttpClientUtils.post(TAOBAO_URL, paramsMap);
		if (StringUtils.isEmpty(retstring) || "null".equals(retstring)) {
			return null;
		}
		try{
			
			Map<String, Object> jsonMap = JsonUtils.parseJSON2Map(retstring);
			if (jsonMap == null || jsonMap.isEmpty()) {
				return null;
			}
			
			if (jsonMap.get("data") != null) {
			
				String dataJsonStr  = jsonMap.get("data").toString();
				jsonMap.clear();
				jsonMap = JsonUtils.parseJSON2Map(dataJsonStr);
				
				ipMessage.setCountry(jsonMap.get("country").toString());
				ipMessage.setArea(jsonMap.get("area").toString());
				ipMessage.setRegion(jsonMap.get("region").toString());
				ipMessage.setCity(jsonMap.get("city").toString());
				ipMessage.setCounty(jsonMap.get("county").toString());
				ipMessage.setIsp(jsonMap.get("isp").toString());
				ipMessage.setIpType(IpUtils.checkIpType(ip).getName());
				ipMessage.setIp(ip);
				ipMessage.setSource(TaoIpCityImpl.class.getName());
			} else {
				return null;
			}
		} catch(Exception e){
			ipMessage = null;
			logger.error(e);
			logger.error("解析出错");
		}
			
		return ipMessage;
	}

}